package com.example.websocket.excel.util;

import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 封装的同步的队列数组
 * 
 * @author guohb
 * 
 */
public class Queue<E> implements Serializable{

	private static final long serialVersionUID = -8685341750914433227L;


	private List<E> list = Collections.synchronizedList(new LinkedList<E>());

	private Object lock = new Object();

	private boolean isQuit = false;

	public E get() {
		synchronized (lock) {
			if (list.size() > 0) {
				return list.remove(0);
			} else {
				try {
					lock.wait();
				} catch (InterruptedException e) {
					throw new RuntimeException("error when waiting for message to be added into the Queue");
				}
				if (!isQuit) {
					return get();
				} else {
					return null;
				}
			}
		}
	}

	public void put(E message) {
		if (message != null) {
			list.add(message);
			synchronized (lock) {
				lock.notifyAll();
			}
		} else {
			throw new RuntimeException(" put a NULL into the Queue,but a Object instance expected");
		}
	}

	public int size() {
		return list.size();
	}

	public void notifyQueue() {
		synchronized (lock) {
			lock.notifyAll();
			this.isQuit = true;
		}
	}

}